<?php

namespace app\admin\service;

use app\admin\validate\ComImagesCateValidate;
use support\spark\model\system\ComImagesCate;
use support\spark\exception\ApiException;

class ComImageCateService
{

    /**
     * 添加分类
     * @param $param
     * @return array
     */
    public function addComImageCate(array $param): array
    {
        // 检验完整性
        $validate = new ComImagesCateValidate();
        if (!$validate->check($param)) {
            throw  new ApiException($validate->getError(), -1);
        }
        $comImagesCateModel = new ComImagesCate();
        $has = $comImagesCateModel->checkUnique([
            'name' => $param['name']
        ]);

        if (!empty($has)) {
            throw  new ApiException('分类名已经存在', -1);
        }
        $param['create_time'] = now();
        $comImagesCateModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑图片分类
     * @param $param
     * @return array
     */
    public function editComImageCate(array $param): array
    {
        // 检验完整性
        // 检验完整性
        $validate = new ComImagesCateValidate();
        if (!$validate->scene('edit')->check($param)) {
            throw  new ApiException($validate->getError(), -1);
        }
        $comImagesCateModel = new ComImagesCate();
        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $comImagesCateModel->checkUnique($where);

        if (!empty($has)) {
            throw  new ApiException('分类名已经存在', -1);
        }
        $comImagesCateModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }

}